from PyQt5.QtWidgets import (QMainWindow, QVBoxLayout, QWidget, QMenuBar, 
                            QStatusBar, QMessageBox, QFileDialog, QAction, QPushButton)
from PyQt5.QtCore import Qt
import logging
from src.ui.widgets.toolbar import Toolbar
from src.ui.widgets.pdf_viewer import PDFViewer
from src.utils.pdf_handler import PDFHandler
from src.utils.pdf_visualizer import PDFSquareVisualizer

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.pdf_handler = PDFHandler()
        self.init_window()
        self.init_menu()
        self.init_statusbar()
        self.init_ui()
        self.connect_signals()

    def init_window(self):
        self.setWindowTitle("PDF编辑器")
        self.setGeometry(100, 100, 1200, 800)
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.layout = QVBoxLayout(self.central_widget)

    def init_menu(self):
        menubar = self.menuBar()
        
        # 文件菜单
        file_menu = menubar.addMenu("文件")
        
        # 打开文件动作
        open_action = QAction("打开", self)
        open_action.setShortcut("Ctrl+O")  # 添加快捷键
        open_action.triggered.connect(self.open_pdf)
        file_menu.addAction(open_action)
        
        # 保存文件动作
        save_action = QAction("保存", self)
        save_action.setShortcut("Ctrl+S")  # 添加快捷键
        save_action.triggered.connect(self.save_pdf)
        file_menu.addAction(save_action)
        
        file_menu.addSeparator()  # 添加分隔符
        
        # 关闭文档动作
        close_action = QAction("关闭文档", self)  # 修改菜单项文字
        close_action.setShortcut("Ctrl+W")  # 添加快捷键
        close_action.triggered.connect(self.close_document)
        file_menu.addAction(close_action)
        
        # 编辑菜单
        edit_menu = menubar.addMenu('编辑')
        self.rotate_left_action = edit_menu.addAction('向左旋转')
        self.rotate_right_action = edit_menu.addAction('向右旋转')

        # 视图菜单
        self.view_menu = menubar.addMenu('视图')
        self.visualize_action = QAction("文字方块可视化", self)
        self.visualize_action.triggered.connect(self.visualize_pdf_as_squares)
        self.view_menu.addAction(self.visualize_action)

    def init_statusbar(self):
        self.statusBar = QStatusBar()
        self.setStatusBar(self.statusBar)
        self.statusBar.showMessage('就绪')

    def connect_signals(self):
        self.rotate_left_action.triggered.connect(lambda: self.rotate_page(-90))
        self.rotate_right_action.triggered.connect(lambda: self.rotate_page(90))
        
        # 连接页面导航信号
        self.toolbar.prev_page_action.triggered.connect(self.pdf_viewer.prev_page)
        self.toolbar.next_page_action.triggered.connect(self.pdf_viewer.next_page)
        self.toolbar.page_changed.connect(self.pdf_viewer.goto_page)  # 连接工具栏页码变更到查看器
        
        # 连接PDF查看器信号
        self.pdf_viewer.pdf_loaded.connect(self.handle_pdf_loaded)
        self.pdf_viewer.page_changed.connect(self.handle_page_changed)  # 连接查看器页码变更到工具栏
        
        # 连接工具栏按钮信号
        self.toolbar.file_open_triggered.connect(self.open_pdf)
        self.toolbar.file_save_triggered.connect(self.save_pdf)
        self.toolbar.fit_page_triggered.connect(self.pdf_viewer.fit_to_page)
        self.toolbar.fit_width_triggered.connect(self.pdf_viewer.fit_to_width)

    def init_ui(self):
        self.toolbar = Toolbar()
        self.pdf_viewer = PDFViewer()
        
        self.layout.addWidget(self.toolbar)
        self.layout.addWidget(self.pdf_viewer)

        self.visualize_squares_button = QPushButton("文字方块可视化")
        self.visualize_squares_button.clicked.connect(self.visualize_pdf_as_squares)
        self.toolbar.addWidget(self.visualize_squares_button)

    def handle_pdf_loaded(self, success, total_pages):
        """处理PDF加载状态变更"""
        if success:
            # 启用页码控件并设置总页数
            self.toolbar.enable_page_controls(True, total_pages)
        else:
            self.toolbar.reset_page_controls()

    def handle_page_changed(self, page_num):
        """处理页码变更"""
        # 确保页码有效再更新工具栏
        if page_num >= 1:
            self.toolbar.update_page_number(page_num)

    def open_pdf(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self, "打开PDF文件", "", "PDF文件 (*.pdf)")
        if file_path:
            if self.pdf_handler.open_pdf(file_path):
                # 先准备工具栏，避免信号触发时工具栏还未准备好
                self.statusBar.showMessage(f'正在加载: {file_path}')
                # 然后加载PDF
                self.pdf_viewer.load_pdf(file_path)
                self.statusBar.showMessage(f'已打开: {file_path}')
                self.current_pdf_path = file_path  # 保存当前PDF路径
            else:
                QMessageBox.critical(self, "错误", "无法打开PDF文件")

    def save_pdf(self):
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存PDF文件", "", "PDF文件 (*.pdf)")
        if file_path:
            if self.pdf_handler.save_pdf(file_path):
                self.statusBar.showMessage(f'已保存: {file_path}')
            else:
                QMessageBox.critical(self, "错误", "无法保存PDF文件")

    def rotate_page(self, angle):
        self.pdf_viewer.rotate_current_page(angle)

    def close_document(self):
        """关闭当前打开的文档"""
        self.pdf_viewer.close_document()
        self.toolbar.reset_page_controls()  # 重置工具栏的控件
        # 更新窗口标题
        self.setWindowTitle("PDF编辑器")
        self.current_pdf_path = None  # 清除当前PDF路径

    def visualize_pdf_as_squares(self):
        """将当前PDF文档可视化为方块"""
        if not hasattr(self, 'current_pdf_path') or not self.current_pdf_path:
            QMessageBox.warning(self, "提示", "请先打开一个PDF文档")
            return
        
        try:
            # 显示加载状态
            self.statusBar.showMessage("正在生成文字方块可视化...")
            
            # 创建可视化器并保存为类成员变量
            self.pdf_visualizer = PDFSquareVisualizer()
            
            # 从PDF查看器获取当前页码
            current_page = self.pdf_viewer.current_page - 1
            if current_page < 0:
                current_page = 0
            
            # 添加错误处理和调试信息
            logging.info(f"正在可视化文档: {self.current_pdf_path}, 页码: {current_page+1}")
            
            # 执行可视化
            self.pdf_visualizer.visualize_pdf(self.current_pdf_path, current_page)
            
            # 更新状态
            self.statusBar.showMessage("文字方块可视化已生成")
            
        except Exception as e:
            import traceback
            logging.error(f"可视化错误: {str(e)}\n{traceback.format_exc()}")
            self.statusBar.showMessage("可视化失败")
            QMessageBox.critical(self, "错误", f"可视化过程中发生错误: {str(e)}")
